﻿using YK.Console.Business.Abstractors;
using YK.Console.Business.OrganizeInfos;

namespace YK.Console.Business.UserStaffInfos;

internal class CreateUserStaffHandler(IUserStaffOperation _operation) : IRequestHandler<CreateUserStaffRequest, Guid>
{
    public Task<Guid> Handle(CreateUserStaffRequest request, CancellationToken cancellationToken)
        => _operation.CreateAsync(request, cancellationToken);
}

internal class UpdateUserStaffHandler(IUserStaffOperation _operation) : IRequestHandler<UpdateUserStaffRequest, Guid>
{
    public Task<Guid> Handle(UpdateUserStaffRequest request, CancellationToken cancellationToken)
        =>_operation.UpdateAsync(request, cancellationToken);
}

internal class DeleteUserStaffHandler(IRepository<UserStaffInfo> _repo,ISender _sender) : IRequestHandler<DeleteUserStaffRequest, int>
{
    public async Task<int> Handle(DeleteUserStaffRequest request, CancellationToken cancellationToken)
    {
        var result =  await _repo.DeleteAsync(x => x.Id == request.Id, cancellationToken);

        //更新部门员工数量
        await _sender.Send(new UpgradeOrgEmployeeCountRequest(request.Id), cancellationToken);

        return result;
    }
}

internal class UserStaffPageHandler(IReadRepository<UserStaffInfo> _repo) : IRequestHandler<UserStaffPageRequest, PaginationResponse<UserStaffOutput>>
{
    public Task<PaginationResponse<UserStaffOutput>> Handle(UserStaffPageRequest request, CancellationToken cancellationToken)
        => _repo.SimplePageAsync<UserStaffOutput>(request, cancellationToken: cancellationToken);
}

internal class GetCurrentUserStaffHandler(IReadRepository<UserStaffInfo> _repo, ICurrentUser _currentUser) : IRequestHandler<GetCurrentUserStaffRequest, List<UserStaffOutput>>
{
    public async Task<List<UserStaffOutput>> Handle(GetCurrentUserStaffRequest request, CancellationToken cancellationToken)
    {
        var userStaffs = await _repo.SetGlobalFilterStatus(ignoreTenantFilter: true, ignoreDataPermissionFilter: true)
                .SimpleListAsync<UserStaffOutput>(x => x.UserId == _currentUser.UserId
                    && x.Enabled == EnabledStatusEnum.Enabled
                    && x.Org.Enabled == EnabledStatusEnum.Enabled
                    && x.Org.Tenant.Enabled == EnabledStatusEnum.Enabled, cancellationToken);

        if (userStaffs.IsNullOrEmpty())
            throw ResultOutput.Exception("非机构员工或机构与员工被停用");

        return userStaffs;
    }
}